// 导航页
import 'package:flower/pages/tabs/detail/flower_detail.dart';
import 'package:flower/pages/tabs/home/children/category.dart';

import 'package:flower/utils/http_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import '../../../components/cached_image_widget.dart';
import '../../../components/swiper.dart';
import '../../../config/service_url.dart';

import '../../../model/category_model.dart';
import '../../../model/flower_list.dart';
import '../../../utils/my_colors.dart';
import '../../../utils/my_icons.dart';
import '../../../utils/self_screen_adaptor.dart';
import 'package:dio/dio.dart';
import 'children/search.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  ScrollController scrollController = ScrollController();
  final TextEditingController _searchController = TextEditingController();
  List<FlowerData> flowerList = [];
  List<CategoryData> categoryList = [];

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    queryFlowerList();
    queryCategoryList();
  }

  //获取分类的数据
  void queryCategoryList() async {
    Response result = await HttpUtil.get(getAllType);
    CategoryModel categoryModel = CategoryModel.fromJson(result.data);
    setState(() {
      categoryList = categoryModel.data!;
    });
  }

//获取花卉总的数据
  void queryFlowerList() async {
    Response result = await HttpUtil.get(getFlowerList);
    FlowerListModel flowerModel = FlowerListModel.fromJson(result.data);
    setState(() {
      flowerList = flowerModel.data!;
    });
  }

  void handleSearch() {
    String keyword = _searchController.value.text;
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SearchFlower(keyword: keyword),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    SelfScreenAdaptor.init(context);
    return Scaffold(
      body: ListView(
          // scrollDirection: Axis.vertical,
          controller: scrollController,
          children: <Widget>[
            search(),
            SizedBox(height: SelfScreenAdaptor.height(40)),
            Swiper(),
            title(),
            title2(),
            titleWidget('花卉分类'),
            SizedBox(height: SelfScreenAdaptor.height(40)),
            categoryIndex(),
            titleWidget('今日精选'),
            curated(),
          ]),
    );
  }

  //分类
  Widget categoryIndex() {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: categoryList.length,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
        crossAxisSpacing: 8.0,
        mainAxisSpacing: 8.0,
      ),
      itemBuilder: (context, index) {
        return GridTile(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              InkWell(
                onTap: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => Category(cid: categoryList[index].id,),
                    ),
                  );
                },
                child: CachedImageWidget(
                  50,
                  50,
                  categoryList[index].img,
                  fit: BoxFit.cover,
                  borderRadius: BorderRadius.circular(25.0), // 半径为宽度或高度的一半
                ),
              ),
              Text(
                categoryList[index].name,
                style: const TextStyle(
                  fontSize: 13.0,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  //搜索
  Widget search() {
    return Container(
      margin: const EdgeInsets.all(9.0),
      padding: const EdgeInsets.symmetric(horizontal: 10.0),
      decoration: BoxDecoration(
        color: MyColors.white,
        border: Border.all(color: MyColors.border), // 添加灰色边框
        borderRadius: BorderRadius.circular(20.0),
      ),
      child: Stack(
        children: <Widget>[
          Positioned(
            child: TextField(
              controller: _searchController,
              decoration: const InputDecoration(
                labelText: '搜索',
                labelStyle: TextStyle(fontSize: 14.0), // 调整标签文本大小
                border: InputBorder.none, // 去掉边框
                contentPadding: EdgeInsets.symmetric(
                    vertical: 0.0, horizontal: 7.0), // 调整内边距以改变高度
              ),
              keyboardType: TextInputType.text, // 设置输入类型
              style: const TextStyle(fontSize: 14.0), // 可选：调整字体大小以进一步减小高度
            ),
          ),
          Container(
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(top: 10.0),
              child: InkWell(
                onTap: () {
                  handleSearch();
                },
                child: const Icon(
                  MyIcons.search,
                  color: MyColors.girlBlue,
                  size: 28,
                ),
              )),
        ],
      ),
    );
  }

  //文字
  Widget title() {
    return Column(
      children: [
        Container(
          alignment: Alignment.topCenter,
          margin: const EdgeInsets.only(top: 15),
          child: const Text(
            "Cute Hand Made",
            style: TextStyle(fontSize: 12, color: MyColors.title),
          ), // 将Swiper组件放置在Expanded中,
        ),
        Container(
          margin: const EdgeInsets.only(top: 0), // 调整上下位置
          width: MediaQuery.of(context).size.width * 0.5, // 设置水平线宽度
          child: const Divider(thickness: 1, color: MyColors.title), // 水平线
        ),
      ],
    );
  }

//文字
  Widget title2() {
    return Container(
      alignment: Alignment.topCenter,
      child: const Text(
        "(创意花店)一秒提成爱情格调",
        style: TextStyle(fontSize: 7, color: MyColors.title),
      ), // 将Swiper组件放置在Expanded中,
    );
  }

//标题
  Widget titleWidget(String title) {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(left: SelfScreenAdaptor.width(10)),
      padding: EdgeInsets.only(left: SelfScreenAdaptor.width(10)),
      height: SelfScreenAdaptor.height(42),
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
                  color: MyColors.title, width: SelfScreenAdaptor.width(10)))),
      child: Text(
        title,
        textAlign: TextAlign.justify,
        style: const TextStyle(color: MyColors.normal),
      ),
    );
  }

  Widget curated() {
    return GridView.builder(
      padding: const EdgeInsets.all(10),
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 10.0,
        mainAxisSpacing: 10.0,
        childAspectRatio: 0.7,
      ),
      itemCount: flowerList.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) =>
                    FlowerDetailPage(flowerId: flowerList[index].id),
              ),
            );
          },
          child: Card(
            elevation: 3,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: ClipRRect(
                    borderRadius:
                        const BorderRadius.vertical(top: Radius.circular(10)),
                    child: CachedImageWidget(
                      double.infinity,
                      double.infinity,
                      flowerList[index].coverUrl,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        flowerList[index].name,
                        style: const TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 5),
                      Text(
                        flowerList[index].ename,
                        style: const TextStyle(
                          fontSize: 14,
                          color: MyColors.ename,
                        ),
                      ),
                      const SizedBox(height: 5),
                      Text(
                        "￥${flowerList[index].price}",
                        style: const TextStyle(
                          fontSize: 14,
                          color: MyColors.red,
                        ),
                      ),
                      const SizedBox(height: 5),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
